package com.jy.api;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * Created by lihu on 2017/12/27.
 */
@Configuration
public class AliProducerConfig {


    private String accessKeyId = "LTAI5tG68scB6Z7EwGY2Q1jx";

    private String accessKeySecret = "P7NhOo4t9bqTr8fdJJ7wPW9q35OT70";

    @Value("${aliyun.propertykeyconst.onsaddr}")
    private String onsaddr;

    @Value("${aliyun.propertykeyconst.producerid}")
    private String producerid;

    @Value("${aliyun.propertykeyconst.topicid}")
    private String topicid;

    @Value("${mns.end-point}")
    private String endPoint;

    private final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
    private final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）


    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ProducerBean onsProducerBean() {
        ProducerBean producerBean = new ProducerBean();
        Properties property = new Properties();
        property.put("topicId", topicid);
        property.put(PropertyKeyConst.ProducerId, producerid);
        property.put(PropertyKeyConst.AccessKey, accessKeyId);
        property.put(PropertyKeyConst.SendMsgTimeoutMillis, "30000");
        property.put(PropertyKeyConst.SecretKey, accessKeySecret);
        // 设置 TCP 接入域名（此处以公共云的公网接入为例）
        property.put(PropertyKeyConst.ONSAddr, onsaddr);
        producerBean.setProperties(property);
        return producerBean;
    }

    @Bean(destroyMethod = "close")
    public MNSClient mnsMNSClientBean() {
        CloudAccount account = new CloudAccount(accessKeyId, accessKeySecret, endPoint);
        //这个client仅初始化一次
        MNSClient client = account.getMNSClient();
        return client;
    }

    @Bean
    public IAcsClient acsClientBean() throws ClientException {
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        return acsClient;
    }


}
